<?php

namespace app\group\controller\admin\order;

use app\group\model\order\GroupTicket;
use app\group\model\order\GroupTicket as GroupTicketModel;
use app\seller\model\Store;
use app\shop\model\order\Aftersale as OrderAftersaleModel;
use app\shop\model\Pay;
use app\shop\model\Pay as PayModel;
use sheep\controller\Backend;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use app\group\service\goods\GoodsService;
use app\shop\model\order\Order as OrderModel;
use app\shop\model\order\OrderItem as OrderItemModel;

class Order extends Backend
{
    public $organ_id;
    public function initialize()
    {
        $this->organ_id = $this->shopId();
        $this->model = new OrderItemModel;
        $this->orderModel = new OrderModel;
        $this->aftersaleModel = new OrderAftersaleModel;
        $this->ticketModel = new GroupTicketModel;
    }

    // 状态选项
    public function getType()
    {
        $status = $this->orderModel->searchStatusList();
        unset($status['paid'], $status['nosend'], $status['noget'], $status['refuse'], $status['nocomment'], $status['aftersale'], $status['applyRefundIng'], $status['refund'], $status['closed']);
        $status_value = [];
        foreach ($status as $key => $value) {
            $status_value[] = [
                'text' => $value,
                'value' => $key,
            ];
        }

        return success('获取成功', $status_value);
    }


    /**
     * 订单列表
     *
     * @return \think\Response
     */
    public function list(Request $request)
    {
        $user = $this->auth()->user();
        $store_id = $this->shopId();
        $param = $request->param();
        $where = [];
//        $orders = $this->model->with(['order', 'user', 'groupTicket'])
//            ->where(['store_id' => $store_id])
//            ->paginate($param)->toArray();
        if ($user->role_id != 1) {
            $where[] = ['shop_order_item.store_id', '=', $store_id];
        }
        if (!empty($param['order_sn'])) {
            $where[] = ['shop_order.order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }
        if (!empty($param['goods_title'])) {
            $where[] = ['shop_order_item.goods_title', 'like', '%' . $param['goods_title'] . '%'];
        }
        if (!empty($param['nickname'])) {
            $where[] = ['user.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        if (!empty($param['mobile'])) {
            $where[] = ['user.mobile', 'like', '%' . $param['mobile'] . '%'];
        }
        if (!empty($param['status'])) {
            // 兼容待使用的值，待优化 可以前端写死传过来  团购已支付的值相当于待使用
            if ($param['status'] == 'unused') {
                $param['status'] = 'paid';
            }
            $where[] = ['shop_order.status', '=', $param['status']];
        }
        if (!empty($param['name'])) {
            $where[] = ['shop_store.name', 'like', '%' . $param['name'] . '%'];
        }
        if (!empty($param['start_time'])) {
            $where[] = ['shop_order_item.create_time', '>=', $param['start_time']];
        }
        if (!empty($param['end_time'])) {
            $where[] = ['shop_order_item.create_time', '<=', $param['end_time']];
        }

        /* $orders = $this->model->alias('shop_order_item')
            ->field('shop_order_item.*,shop_order.order_sn,shop_order.status, shop_order.paid_time, shop_order.remark, shop_order.create_time,user.nickname,user.mobile,shop_store.name')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_item.order_id')
            ->leftJoin('user', 'user.id = shop_order_item.user_id')
            ->leftJoin('shop_store', 'shop_store.id = shop_order_item.store_id')
            ->where(['shop_order.type' => 'group'])
            ->where($where)
            ->order('shop_order_item.create_time', 'desc')
            ->paginate($param)->toArray(); */


        $orders = $this->orderModel->alias('shop_order')
            ->field('shop_order.order_sn,shop_order.status,shop_order.activity_type,shop_order.invoice_status,shop_order.platform,shop_order.apply_refund_status,shop_order.type,shop_order_item.*,user.nickname,user.mobile,shop_store.name')
            ->rightJoin('shop_order_item', 'shop_order.id = shop_order_item.order_id')
            ->leftJoin('user', 'user.id = shop_order.user_id')
            ->leftJoin('shop_store', 'shop_store.id = shop_order_item.store_id')
            ->where(['shop_order.type' => 'group'])
            ->where($where)
            ->order('shop_order.create_time', 'desc')
            ->paginate($param)->toArray();

        // 未使用 已过期的核销码
        $expiredWrite = $this->ticketModel
            ->field('id, code, status, validity_time, order_id, order_item_id')
            ->where('status', '=', 0)
            ->where('validity_time', '<', time())
            ->select();

        if (!$expiredWrite->isEmpty()) {
            $cutepetDb             = Db::connect('mysql_cutepet');
            foreach ($expiredWrite as $expired) {
                GroupTicketModel::update(['status' => -2, 'use_time' => time()], ['id' => $expired['id']]);
                $cutepetDb->name('group_ticket')->where('code', $expired['code'])->update(['status' => -2, 'use_time' => time()]);
            }
        }

        $status_list = $this->orderModel->searchStatusList();
        unset($status_list['closed'], $status_list['pending'], $status_list['nosend'], $status_list['noget'], $status_list['refuse'], $status_list['nocomment'], $status_list['aftersale'], $status_list['applyRefundIng'], $status_list['refund']);

        foreach ($orders['data'] as $key => $value) {
            $orders['data'][$key]['validity_time'] = $value['validity_time'] ? date('Y-m-d H:i:s', $value['validity_time']) : '';
//            $all_tickets = GroupTicketModel::where(['order_item_id' => $value['id'], 'status' => 0])->count();
            $orders['data'][$key]['group_ticket_count'] = GroupTicketModel::where(['order_item_id' => $value['id'], 'status' => 1])->count();

            if ($value['status'] == OrderModel::STATUS_PAID) {
                $orders['data'][$key]['status_text'] = $status_list[OrderModel::STATUS_UNUSED];
            } else {
                $orders['data'][$key]['status_text'] = $status_list[$value['status']];
            }

        }

        return success('获取成功', $orders);
    }

    /**
     * 订单详情
     *
     * @return \think\Response
     */
    public function detail(Request $request, $id)
    {
        $write_off_detail = $this->model
            ->alias('shop_order_item')
            ->field('shop_order_item.*,shop_order.order_sn, shop_order.paid_time, shop_order.remark, shop_order.create_time')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_item.order_id')
            ->where('shop_order_item.id', $id)->with(['order', 'pay', 'groupTicket'])
            ->find();
        return success('获取成功', $write_off_detail);
    }

    /**
     * 订单记录
     *
     * @return \think\Response
     */
    public function detailLog(Request $request, $id)
    {
        $write_off_detail = $this->model
            ->field('shop_order.order_sn')
            ->alias('shop_order_item')
            ->field('shop_order_item.*,shop_order.order_sn')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_item.order_id')
            ->where('shop_order_item.id', $id)->with(['groupTicket'])
            ->find()->toArray();
        $write_off_detail['order_num'] = $this->model->where('id', $write_off_detail['order_id'])->count();
        foreach ($write_off_detail['groupTicket'] as $key => $value) {
            $write_off_detail['groupTicket'][$key]['write_price'] = $write_off_detail['pay_fee'];
        }

        return success('获取成功', $write_off_detail);
    }

    // 售后订单
    public function aftersale(Request $request)
    {
        // $store_id = $this->shopId();
        $param = $request->param();
        $where = [];

        if (!empty($param['aftersale_sn'])) {
            $where[] = ['shop_order_afters.aftersale_sn', 'like', '%' . $param['aftersale_sn'] . '%'];
        }
        if (!empty($param['order_sn'])) {
            $where[] = ['shop_order.order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }
        if (!empty($param['goods_title'])) {
            $where[] = ['shop_order_afters.goods_title', 'like', '%' . $param['goods_title'] . '%'];
        }
        if (!empty($param['nickname'])) {
            $where[] = ['user.nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        if (!empty($param['mobile'])) {
            $where[] = ['user.mobile', 'like', '%' . $param['mobile'] . '%'];
        }
        if (!empty($param['name'])) {
            $where[] = ['shop_store.name', 'like', '%' . $param['name'] . '%'];
        }
        if (!empty($param['start_time'])) {
            $where[] = ['shop_order_afters.create_time', '>=', $param['start_time']];
        }
        if (!empty($param['end_time'])) {
            $where[] = ['shop_order_afters.create_time', '<=', $param['end_time']];
        }

        $orders = $this->aftersaleModel->alias('shop_order_afters')
            ->field('shop_order_afters.*,shop_order.order_sn,shop_order.status, shop_order.paid_time, shop_order.remark, shop_order.create_time,user.nickname,user.mobile,shop_store.name')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_afters.order_id')
            ->leftJoin('shop_order_item', 'shop_order_item.id = shop_order_afters.order_item_id')
            ->leftJoin('user', 'user.id = shop_order_afters.user_id')
            ->leftJoin('shop_store', 'shop_store.id = shop_order_item.store_id')
            ->where($where)
            ->paginate($param)->toArray();

        return success('获取成功', $orders);
    }

    /**
     * 售后订单详情
     *
     * @return \think\Response
     */
    public function aftersale_detail(Request $request, $id)
    {
        $write_off_detail = $this->model
            ->field('shop_order_item.*,shop_order.order_sn, shop_order.paid_time, shop_order.remark, shop_order.create_time')
            ->alias('shop_order_item')
            ->field('shop_order_item.*,shop_order.order_sn')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_item.order_id')
            ->where('shop_order_item.id', $id)->with(['order', 'pay', 'groupTicket'])
            ->find();
        return success('获取成功', $write_off_detail);
    }

    /**
     * 售后订单记录
     *
     * @return \think\Response
     */
    public function aftersale_log(Request $request, $id)
    {
        $write_off_detail                = $this->aftersaleModel
            ->alias('shop_order_afters')
            ->field('shop_order_afters.*,shop_order.order_sn,user.nickname')
            ->leftJoin('shop_order', 'shop_order.id = shop_order_afters.order_id')
            ->leftJoin('user', 'user.id = shop_order_afters.user_id')
            ->where('shop_order_afters.order_item_id', $id)
            ->find()->toArray();
        $write_off_detail['order_num']   = $this->model->where('id', $write_off_detail['order_item_id'])->count();
        $write_off_detail['groupTicket'] = [];
        $write_off_detail['pay']         = [];
        if (!empty($write_off_detail)) {
            $write_off_detail['pay']         = Pay::where('order_id', $write_off_detail['order_id'])->find();
            $write_off_detail['groupTicket'] = GroupTicket::where('order_item_id', $write_off_detail['order_item_id'])->select();
        }

        return success('获取成功', $write_off_detail);
    }
}